<template>
    <div style="width: 500px;background: #ffffff;">
        <el-form label-width="100">
            <el-form-item label="SSE服务地址">
                <el-input v-model="sseAddress" placeholder=""></el-input>
            </el-form-item>
            <el-form-item label="SSE请求响应">
                <el-input type="textarea" v-model="text" :rows="20" placeholder=""></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="send">发送</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
const sseAddress = ref('/api/demoSse/mvcSse');
const text = ref('');

const emitSourceRef = ref(null);

const send = () => {

    if (!sseAddress.value) {
        ElMessage.warning('请输入地址');
        return;
    }
    let emitSource = emitSourceRef.value;
    emitSource = new EventSource(sseAddress.value)
    text.value = '';
    // emitSource.onopen = () => {
    //     console.log('连接成功');
    // };
    // emitSource.onmessage = (event) => {
    //     console.log(event.data);
    //     if (event.data === '[DONE]') {
    //         emitSource.close();
    //         return;
    //     }
    //     text.value += event.data + '\n';
    // };
    // emitSource.onerror = (error) => {
    //     console.log(error);
    //     ElMessage.error('连接失败:' + error);
    // };
    emitSource.addEventListener('open', () => {
        console.log('连接成功');
    });
    emitSource.addEventListener('message', (event) => {
        console.log(event.data);
        if (event.data === '[DONE]') {
            emitSource.close();
            return;
        }
        text.value += event.data + '\n';
    });
    emitSource.addEventListener('error', (error) => {
        console.log(error);
        ElMessage.error('连接失败:' + error);
    });
    emitSourceRef.value = emitSource;
};
</script>